package xy.come.juhenews.Fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import xy.come.juhenews.Activity.NewsDetailsActivity;
import xy.come.juhenews.Adapter.NewsListAdapter;
import xy.come.juhenews.Base.BaseFragment;
import xy.come.juhenews.Bean.NewsBean;
import xy.come.juhenews.Http.Constant;
import xy.come.juhenews.R;
import xy.come.juhenews.Uitils.LoadingDialog;
import xy.come.juhenews.Uitils.LogUtils;
import xy.come.juhenews.Widget.CircularAnim;

/**
 * Created by Xia_焱 on 2018/7/11.
 * e-mail：XiahaotianV@163.com
 */

public class NewsFragment extends BaseFragment {
    @BindView(R.id.rc_list)
    RecyclerView rcList;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.ll_null)
    AutoLinearLayout llNull;
    private List<NewsBean.ResultBean.DataBean> newsDataList;
    private NewsListAdapter mAdapter;
    private static final int PAGE_SIZE = 5;
    private String titleId;
    private int colour;
    private LoadingDialog loadingDialog;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_news;
    }

    @Override
    public void initData() {
        newsDataList = new ArrayList<>();


    }


    @Override
    protected void initView() {
        initRefreshLayout();


    }

    @Override
    protected void lazyLoad() {
        initialize();
        initAdapter();
        refresh();
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, final int position) {

                CircularAnim.fullActivity(getActivity(), view)
                        .colorOrImageRes(R.mipmap.icon_bg_x)
                        .go(new CircularAnim.OnAnimationEndListener() {
                            @Override
                            public void onAnimationEnd() {
                                Intent intent = new Intent(getActivity(), NewsDetailsActivity.class);
                                String url = newsDataList.get(position).getUrl();
                                intent.putExtra("url", url);
                                startActivity(intent);
                            }
                        });

            }
        });
    }

    public String setTitle(String str) {
        titleId = str;
        return str;
    }


    private void initRefreshLayout() {
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }

    private void initAdapter() {
        mAdapter = new NewsListAdapter(R.layout.item_news_list, newsDataList);
        mAdapter.openLoadAnimation();
        rcList.setAdapter(mAdapter);
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        });


    }

    private void initialize() {
        swipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        rcList.setLayoutManager(new LinearLayoutManager(getActivity()));
        loadingDialog = new LoadingDialog(getActivity());

    }

    private void refresh() {
        loadingDialog.LoadingShow();
        mAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        OkHttpUtils.post()
                .addParams("type", titleId)
                .addParams("key", Constant.Key)
                .url(Constant.NEWS_LIST).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mAdapter.loadMoreFail();
                loadingDialog.LoadingDismiss();
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.e(response);
                try {
                    JSONObject object = new JSONObject(response);
                    String reason = (String) object.get("reason");
                    if (reason.equals("超过每日可允许请求次数!")) {
                        llNull.setVisibility(View.VISIBLE);
                        swipeLayout.setVisibility(View.GONE);
                        rcList.setVisibility(View.GONE);
                        loadingDialog.LoadingDismiss();
                    } else {
                        llNull.setVisibility(View.GONE);
                        swipeLayout.setVisibility(View.VISIBLE);
                        rcList.setVisibility(View.VISIBLE);
                        NewsBean newsData = JSON.parseObject(response, NewsBean.class);
                        List<NewsBean.ResultBean.DataBean> data = newsData.getResult().getData();
                        if (data != null) {
                            newsDataList.clear();
                            newsDataList.addAll(data);
                            setData(true, newsDataList);
                            mAdapter.setEnableLoadMore(true);
                            swipeLayout.setRefreshing(false);
                            loadingDialog.LoadingDismiss();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                loadingDialog.LoadingDismiss();

            }
        });

    }

    private void loadMore() {
        OkHttpUtils.post()
                .addParams("type", titleId)
                .addParams("key", Constant.Key)
                .url(Constant.NEWS_LIST).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mAdapter.loadMoreFail();
            }

            @Override
            public void onResponse(String response, int id) {
                LogUtils.e(response);
                NewsBean newsData = JSON.parseObject(response, NewsBean.class);
                List<NewsBean.ResultBean.DataBean> data = newsData.getResult().getData();
                if (data != null) {
                    newsDataList.addAll(data);
                    setData(false, newsDataList);
                }

            }
        });
    }

    private void setData(boolean isRefresh, List<NewsBean.ResultBean.DataBean> list) {
        final int size = list == null ? 0 : list.size();
        Log.e("XXX", size + "");
        if (isRefresh) {
            mAdapter.setNewData(list);

        } else {
            if (size > 0) {
                mAdapter.addData(list);
            } else {

            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
            //Toast.makeText(activity, "没有更多数据了", Toast.LENGTH_SHORT).show();
        } else {
            mAdapter.loadMoreComplete();
        }
    }

}
